/**
* @description  : 案件统计
* @descriptionDetail : 案件统计
* @copyright    : 浙江烟草
* @author       : mc
* @create       : 2022-12-05 13:56:42
*/
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="nav-right-icon">
        <u-icon name="reload" color="#FFF" @tap="refreshTb()"></u-icon>
        <u-icon style="margin-left: 20rpx" name="more-dot-fill" color="#FFF" @tap="showSearch = true"></u-icon>
      </view>
    </theme-navbar>
    <!-- #endif -->
    <!-- #ifdef H5-DINGDING || H5-WECHAT || H5-EMP -->
    <fab-button :content="fContent" @fabtrigger="fabtrigger" />
    <!-- #endif -->
    <view class="content u-page">
      <warehouse-stats-com
          :totalTitle="orginalData.content.length == 1 ? orginalData.content[0].orgName : '合计'"
          :hasTotalRow="hasTotal"
          :needCalcTotal="false"
          :totalEndOrStart="hasTotal"
          :fixedLimit="10"
          :keyCode="keyCode"
          :itemKeyUuid="itemKeyUuid"
          :orginalData="orginalData"
          :header="header"
          :height="swiperHeight"
          :tabCurrent="tabCurrent"
          areaKey="org_name"
          @dbClick="dbClick"
          @clickItem="clickItem">
      </warehouse-stats-com>
      <u-tabbar bg-color="#F7F7F9" activeColor="rgb(0 112 210)" v-model="tabCurrent" :list="tabList" icon-size="40" :height="100"
                @change="tabChange"></u-tabbar>
    </view>
    <u-popup mode="right" length="80%" v-model="showSearch" :mask-close-able="maskCanClose">
      <case-search-com ref="lscRef" :regs="regs" :endDate="endDate" :curTimeStart="curTimeStart" :currentPro="currentPro"
                       :curTimeEnd="curTimeEnd" @choiceTime="timeChoice" @search="searchTap" @currentFn="currentFn"
                       @clearCurrent="clearCurrent"></case-search-com>
    </u-popup>
    <u-picker :startYear="startYear" :endYear="endYear" v-model="showTime" mode="time" :params="pickParam"
              @confirm="timeChange"></u-picker>
  </view>
</template>
<script>
import WarehouseStatsCom from './components/warehouse-stats-com.vue';
import CaseSearchCom from './components/caseSearchCom.vue';
import reportService from '@/service/report/report.service.js';
import commonService from '@/service/common/common.service.js';
import moment from 'moment';
import fabButton from '@/components/uni-fab.vue';
export default {
  components: {
    WarehouseStatsCom,
    CaseSearchCom,
    fabButton,
  },
  data () {
    return {
      navTitle: '查获库',
      hasTotal: true, // 是否需要合计
      from: 'ckwptj', // ajzj  zyaj  jyaj zsyaj
      currentPro: 0,
      user: this.$store.state.userInfo,
      keyCode: 'org_uuid',
      itemKeyUuid: '',
      itemKeyName: '',
      pickParam: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false,
        timestamp: true, // 1.3.7版本提供
      },
      fromEnum: {
        ajzj: {
          name: '案件总计',
          propType: '',
        },
        zyaj: {
          name: '真烟案件',
          propType: '01',
        },
        jyaj: {
          name: '假烟案件',
          propType: '02',
        },
        zsyaj: {
          name: '走私烟案件',
          propType: '03',
        },
        ckwptj: {
          name: '查获库',
          propType: '04',
        }
      },
      regs: '',
      showSearch: false,
      showTime: false,
      maskCanClose: true,
      tabCurrent: 0,
      endDate: this.$u.timeFormat(Date.now(), "yyyy-mm-dd"),
      curTimeStart: moment().startOf('year').format('YYYY-MM-DD'),
      curTimeEnd: moment().subtract(1, 'days').format('YYYY-MM-DD'),
      endYear: new Date().getFullYear(),
      startYear: 1950,
      tabList: [
          {
            iconPath: '../../../static/storage/icon_qy.png',
            selectedIconPath: '../../../static/storage/icon_qyb.png',
            text: '查获库',
            header: [
              [{
                label: '',
                fieldKey: 'orgName',
                columnSpan: 3,
                hasSort: false,
                align: 'center',
              },  {
                label: '真烟',
                fieldKey: 'realQty',
                columnSpan: 3,
                hasSort: false,
                align: 'center',
              },
                {
                  label: '假烟',
                  fieldKey: 'fakeQty',
                  columnSpan: 3,
                  hasSort: true,
                  align: 'center',
                },
                {
                  label: '走私烟',
                  fieldKey: 'runQty',
                  columnSpan: 3,
                  hasSort: true,
                  align: 'center',
                },],
              [      {
                label: '单位',
                fieldKey: 'orgName',
                columnSpan: 3,
                hasSort: false,
                align: 'center',
              },      {
                label: '烟叶烟丝等辅料',
                fieldKey: 'yanyeQty',
                columnSpan: 3,
                hasSort: true,
                align: 'center',
              },
              ]
            ]
          },
          {
            iconPath: '../../../static/storage/icon_pg.png',
            selectedIconPath: '../../../static/storage/icon_pgb.png',
            text: '罚没',
            header: [
              [{
                label: '单位',
                fieldKey: 'orgName',
                columnSpan: 3,
                hasSort: false,
                align: 'center',
              },  {
                label: '真烟',
                fieldKey: 'realQty',
                columnSpan: 3,
                hasSort: false,
                align: 'center',
              },
                {
                  label: '假烟',
                  fieldKey: 'fakeQty',
                  columnSpan: 3,
                  hasSort: true,
                  align: 'center',
                },
                {
                  label: '走私烟',
                  fieldKey: 'runQty',
                  columnSpan: 3,
                  hasSort: true,
                  align: 'center',
                },],
              [      {
                label: '单位',
                fieldKey: 'orgName',
                columnSpan: 3,
                hasSort: false,
                align: 'center',
              },      {
                label: '烟叶烟丝等辅料',
                fieldKey: 'yanyeQty',
                columnSpan: 3,
                hasSort: true,
                align: 'center',
              },
              ]
            ]
          },
          {
            iconPath: '../../../static/storage/icon_ly.png',
            selectedIconPath: '../../../static/storage/icon_lyb.png',
            text: '代保管',
            header: [
            [{
              label: '单位',
              fieldKey: 'orgName',
              columnSpan: 3,
              hasSort: false,
              align: 'center',
            },  {
              label: '真烟',
              fieldKey: 'realQty',
              columnSpan: 3,
              hasSort: false,
              align: 'center',
            },
              {
                label: '假烟',
                fieldKey: 'fakeQty',
                columnSpan: 3,
                hasSort: true,
                align: 'center',
              },
              {
                label: '走私烟',
                fieldKey: 'runQty',
                columnSpan: 3,
                hasSort: true,
                align: 'center',
              },],
                [      {
                  label: '单位',
                  fieldKey: 'orgName',
                  columnSpan: 3,
                  hasSort: false,
                  align: 'center',
                },      {
                  label: '烟叶烟丝等辅料',
                  fieldKey: 'yanyeQty',
                  columnSpan: 3,
                  hasSort: true,
                  align: 'center',
                },
                ]
            ]
          },
      ],
      swiperHeight: 0,
      orginalData: {
        header: [],
        content: [],
      },
      header: [],
      orgParam: {
        // org层级相关参数
        orgUuid: '',
        parentOrgUuid: '',
        orgName: '',
        parentOrgName: '',
        orgRank: 1, // 下钻默认是1 表示当前
      },
      fContent: [{
        iconPath: require('@/static/refresh.png'),
        selectedIconPath: require('@/static/refresh.png'),
        text: '刷新',
        active: false,
      },
        {
          iconPath: require('@/static/sou.png'),
          selectedIconPath: require('@/static/sou.png'),
          text: '筛选',
          active: false,
        },
      ],
    };
  },
  onLoad (opt) {
    this.from = opt.from || 'ckwptj';
    this.showDefaultTitle = false;
  },
  watch: {
    showTime (v) {
      // 调用钉钉标题接口，动态设置展示标题
      this.maskCanClose = !v;
    },
  },
  mounted () {
    // this.setRightBtns();
    this.updateMixinTitle(this.fromEnum[this.from].name);
    this.tabList.forEach((itm) => {
      itm.header.forEach((ip) => {
        ip[0].label = this.fromEnum[this.from].name;
      });
    });
    this.init();
    this.currentFn();
  },
  methods: {
    init () {
      // #ifdef H5-DINGDING
      this.swiperHeight = this.$u.sys().windowHeight - 50;
      // #endif
      // #ifndef H5-DINGDING
      this.swiperHeight = this.$u.sys().windowHeight - 44 - 50;
      // #endif
      commonService.queryAreaBaseByCode(this.user.user.org.orgUuid).then((res) => {
        if (!res.success) return;
        let areaName = '';
        let areaCode = '';
        areaName = res.bean.proname;
        areaCode = res.bean.procode;
        this.orgParam.orgName = areaName;
        this.orgParam.areaName = areaName;
        this.orgParam.areaCode = areaCode;
        this.regs = this.orgParam.orgName;
      });
      this.orgParam.parentOrgUuid = '';
      this.orgParam.orgLevel = '01';
      this.orgParam.orgUuid = this.user.user.org.orgUuid; // 默认都用自己地区的code
      this.orginalData.header = this.tabList[this.tabCurrent].header;
      this.loadData();
    },
    currentFn (e) {
      this.currentPro = e;
    },
    clearCurrent () {
      this.currentPro = 0;
    },
    setRightBtns () {
      // 设置右侧标题
      // #ifdef H5-DINGDING
      this.$deviceApi.setMenu([{
            id: '1',
            text: '刷新',
          },
            {
              id: '2',
              text: '更多',
            },
          ],
          (res) => {
            if (res.id == '1') {
              this.refreshTb();
            } else {
              // 弹出more
              this.showSearch = true;
            }
          }
      );
      // #endif
    },
    loadData () {
      // this.$modal.showLoading('查询中...');
      let cts = this.curTimeStart;
      let cte = this.curTimeEnd;
      let param = {
        caseStartTime: cts,
        caseEndTime: cte,
        part: '',
        caseCode: '',
        storeType: '',
      };
      if (this.tabCurrent == 0) {
        param.storeType = '02'
      } else if (this.tabCurrent == 1){
        param.storeType = '03'
      } else if (this.tabCurrent == 2){
        param.storeType = '05'
      }
      reportService
          .caseStatisticsCom(param)
          .then((res) => {
            this.$modal.hideLoading();
            if (res.success) {
              // 如果合计在最后一行
              if (res.data.length > 0) {
                let totalRow = res.data[res.data.length - 1];
                if (totalRow.orgName == '全省') {
                  res.data.splice(res.data.length - 1, 1);
                  res.data.unshift(totalRow);
                }
                if (this.hasTotal) {
                  let num1 = 0;
                  let num2 = 0;
                  let num3 = 0;
                  let num4 = 0;
                  console.log('res.data', res.data)
                  for (let i = 1; i < res.data.length; i++) {
                    if (res.data[i].realQty) {
                      num1 += parseFloat(res.data[i].realQty);
                    }
                    if (res.data[i].fakeQty) {
                      num2 += parseFloat(res.data[i].fakeQty);
                    }
                    if (res.data[i].runQty) {
                      num3 += parseFloat(res.data[i].runQty);
                    }
                    if (res.data[i].yanyeQty) {
                      num4 += parseFloat(res.data[i].yanyeQty);
                    }
                  }
                  // res.data[0].realQty = num1;
                  // res.data[0].fakeQty = num2;
                  // res.data[0].runQty = num3;
                  // res.data[0].yanyeQty = num4;
                }
                res.data.forEach((item) => {
                  if (!item.case_total_val) {
                    item.case_total_val = 0;
                  }
                  if (item.c_case_count) {
                    item.proportion_c_case_count = ((item.c_case_count / res.data[0].c_case_count) * 100).toFixed(2) + '%';
                  } else {
                    item.proportion_c_case_count = '';
                  }
                  if (item.g_count) {
                    item.proportion_g_count = ((item.g_count / res.data[0].g_count) * 100).toFixed(2) + '%';
                  } else {
                    item.proportion_g_count = '';
                  }
                  if (item.case_total_val) {
                    item.proportion_case_total_val = ((item.case_total_val / res.data[0].case_total_val) * 100).toFixed(2) + '%';
                  } else {
                    item.proportion_case_total_val = '';
                  }

                  if (item.proportion_c_case_count) {
                    item.proportion_c_case_count = Number(item.proportion_c_case_count.replace('%', ''));
                  }
                  if (item.proportion_g_count) {
                    item.proportion_g_count = Number(item.proportion_g_count.replace('%', ''));
                  }
                  if (item.proportion_case_total_val) {
                    item.proportion_case_total_val = Number(item.proportion_case_total_val.replace('%', ''));
                  }

                  if (item.percent_c_case_count) {
                    item.percent_c_case_count = Number(item.percent_c_case_count.replace('%', ''));
                  }
                  if (item.percent_g_count) {
                    item.percent_g_count = Number(item.percent_g_count.replace('%', ''));
                  }
                  if (item.percent_case_total_val) {
                    item.percent_case_total_val = Number(item.percent_case_total_val.replace('%', ''));
                  }
                });
              }
              this.orginalData.content = this.$u.deepClone(res.data);
              // this.endDate = cte;
            } else {
              this.$u.toast(res.msg);
            }
          })
          .catch((e) => {
            this.$modal.hideLoading();
            console.log(e);
            this.$u.toast('查询失败');
          });
    },
    tabChange (e) {
      console.log('e====' + e);
      this.tabCurrent = e;
      this.navTitle = this.tabList[this.tabCurrent].text;

      this.keyCode = this.tabCurrent == 0 ? 'org_uuid' : '';
      this.orginalData.header = this.tabList[this.tabCurrent].header;
      this.orginalData.content = [];

      this.updateMixinTitle(this.tabList[this.tabCurrent].text);
      this.tabList.forEach((itm) => {
        itm.header.forEach((ip) => {
          ip[0].label = this.tabList[this.tabCurrent].text;
        });
      });

      this.loadData();
    },
    dbClick (obj) {
      if (this.tabCurrent != 0) return;
      if (this.orgParam.orgRank > 1) return;
      // if(this.user.orgLevel == 3) return;
      this.orgParam.parentOrgUuid = this.orgParam.orgUuid;
      this.orgParam.parentOrgName = this.orgParam.orgName;
      this.orgParam.orgUuid = obj.org_uuid;
      this.orgParam.orgName = obj.org_name;
      this.orgParam.orgLevel = obj.org_level;
      this.orgParam.orgRank++;
      this.itemKeyUuid = '';
      this.itemKeyName = '';
      this.hasTotal = false;
      this.loadData();
    },
    clickItem (itm, key) {
      if (this.tabCurrent != 0) return;
      this.itemKeyUuid = itm.org_uuid;
      this.orgParam.orgLevel = itm.org_level;
      this.itemKeyName = itm.orgShortName;
    },
    refreshTb () {
      // 刷新操作，刷新暂不重置筛选条件
      this.orgParam.parentOrgUuid = '';
      this.orgParam.parentOrgName = '';
      this.itemKeyUuid = '';
      // this.endDate = moment().subtract(1, 'days').format("YYYY-MM-DD");
      // this.curTimeStart = moment().startOf('year').format('YYYY-MM-DD');
      // this.curTimeEnd = moment().subtract(1, 'days').format("YYYY-MM-DD");this.user.user.org.orgUuid
      this.orgParam.orgUuid = this.user.user.org.orgUuid; // 默认都用省的code
      this.orgParam.orgLevel = '01'; // "0" + this.user.orgLevel;
      this.orgParam.orgName = this.orgParam.areaName;
      this.orgParam.orgRank = 1;
      this.hasTotal = true;
      this.loadData();
    },
    timeChoice (f) {
      this.showTimeFlag = f;
      this.showTime = true;
    },
    timeChange (e) {
      const yesterday = moment().subtract(1, 'days').format('X');
      const choseTime = e.timestamp;
      if (Number(choseTime) > Number(yesterday)) {
        this.$u.toast('所选日期不能大于昨日');
        return false;
      }
      if (this.showSearch) {
        if (this.showTimeFlag == 0) {
          this.$refs.lscRef.timeOverStart = e.year + '-' + e.month + '-' + e.day;
        } else {
          this.$refs.lscRef.timeOverEnd = e.year + '-' + e.month + '-' + e.day;
        }
      }
    },
    searchTap (e) {
      if (e.isReset) {
        this.refreshTb();
      } else {
        this.showSearch = false;
        this.curTimeStart = e.data.timeOverStart;
        this.curTimeEnd = e.data.timeOverEnd;
        this.loadData();
      }
    },
    fabtrigger (act) {
      if (act.index === 0) {
        this.refreshTb();
      } else if (act.index === 1) {
        this.showSearch = true;
      }
    },
  },
};
</script>
<style scoped lang="scss">
.page {
  padding: 0;
}

.nav-right-icon {
  margin-right: 30rpx;
  font-size: 0.8rem;
  color: #fff;
}

.regie {
  height: 88rpx;
  padding: 0 $cm-content-paddng-row;
  font-size: 28rpx;
  display: inline-flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}

.regie_txt_normal {
  font-weight: 400;
  color: #989ea1;
}

.regie_txt {
  font-weight: 600;
  color: #0070d2;
}

.regie_txt_divider {
  font-size: 12rpx;
  margin-left: 12rpx;
  margin-right: 12rpx;
}
</style>
